'use strict';

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

var mimetypes = {
    ".html":"text/html",
    ".png":"image/png",
    ".jpg":"image/jpeg",
    ".css":"text/css",
    ".js":"text/javascript",
    ".svg":"image/svg+xml"
};

var server = http.createServer(function (req, res) {
    var p, originalp, absp, u;
    u = url.parse(req.url);
    try {
        p = decodeURIComponent(u.pathname);
        // prune head /
        while (p[0] === '/') {
            p = p.substr(1);
        }
    } catch (e) {
        res.writeHead(400, {'Content-Type': 'text/plain'});
        res.end(e.toString());
        return;
    }
    originalp = p;
    if (p === "") {
        p = "web_run.html";
    } else {
        p = (function (p) {
            var split, ret, i, l;
            split = p.split('/');
            ret = [];
            for (i = 0, l = split.length; i < l; ++i) {
                if (split[i] === '..') {
                    ret.pop();
                } else {
                    ret.push(split[i]);
                }
            }
            return ret.join('/');
        }(p));
    }
    absp = path.resolve(__dirname, p);
    fs.stat(absp, function (err, stats) {
        if (err !== null) {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end(err.toString());
        } else {
            if (stats.isDirectory()) {
                // when a directory is requested with only its name
                // without ending slash we redirect to correct url
                if (p.charAt(p.length - 1) !== '/') {
                    u.pathname += '/';
                    u.host = req.headers.host;
                    u.protocol = 'http';
                    res.writeHead(302, {'Location': url.format(u) });
                    res.end();
                } else {
                    absp += '/index.html';
                    p += 'index.html';
                    sendFile(absp, p);
                }
            } else {
                // we don't test if file exists here since the
                // readFile will handle that in sendFile
                sendFile(absp, p);
            }
        }
    });

    function sendFile(p, relp) {
        var ext = path.extname(p).toLowerCase();
        var mt;
        mt = mimetypes[ext] || 'application/octet-stream';

        fs.readFile(p, function(err, data) {
            if (err !== null) {
                res.writeHead(404, {'Content-Type': 'text/plain'});
                res.end(err.toString());
            } else {
                // note that we use no-store here since no-cache does
                // not work for Chrome that still caches
                var headers = {
                    'Content-Type': mt, 
                    'Cache-Control': 'no-store, no-cache', 
                    'Pragma': 'no-cache', 
                    'Expires': 0,
                    'X-UA-Compatible': 'IE=edge'
                };
                res.writeHead(200, headers);
                res.end(data);
            }
        });
    }
    
});

server.listen(process.env.VMC_APP_PORT || 1337, function () {
    console.log("listening on %j", server.address());
});

